package com.excesys.exsecs.energy.task;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.excesys.exsecs.alarm.dto.RunFlyOrLow;
import com.excesys.exsecs.alarm.judgment.JudgmentInvoke;
import com.excesys.exsecs.energy.constant.RedisConstants;
import com.excesys.exsecs.energy.entity.*;
import com.excesys.exsecs.energy.mapper.RegDevMapper;
import com.excesys.exsecs.energy.service.*;
import com.excesys.exsecs.energy.util.DateUtil;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import static cn.hutool.core.date.DateTime.now;

/**
 * @author liuzhikun
 * @title: PowerTask
 * @projectName pig
 * @description: 能耗定时任务
 * @date 2023/5/1711:19
 */
@Slf4j
@Component
@AllArgsConstructor
public class PowerTask {

    private final StringRedisTemplate redisTemplate;
    private final PowerHourFlowService powerHourFlowService;
    private final PowerDayFlowService powerDayFlowService;
    private final PowerMonthFlowService powerMonthFlowService;
    private final WaterHourFlowService waterHourFlowService;
    private final WaterDayFlowService waterDayFlowService;
    private final WaterMonthFlowService waterMonthFlowService;
    private final RegDevMapper regDevMapper;
    private final EnergyRateManageService energyRateManageService;
    private final EnergyRateFlowService energyRateFlowService;
    private final CostHourFlowService costHourFlowService;
    private final AmmeterResetService ammeterResetService;
    private final PowerExceptionFlowService powerExceptionFlowService;
    private final JudgmentInvoke judgment;

    /**
     * 电表能耗流水定时任务
     */
    @Scheduled(cron = "0 0/10 * * * ?")
    private String insertPowerFlowHandler() {
        Integer debug = 0;
        log.info("insertPowerFlowHandler------start");
        Date currentDate = DateUtil.getSecondPoint(now());
        boolean oClock = DateUtil.oClock(new DateTime(currentDate));
        boolean oClockDay = DateUtil.oClockDay(now());
        boolean oClockMonth = DateUtil.oClockMonth(now());
        if (debug.compareTo(1) == 0) {
            oClock = true;
        }
        if (!oClock && !oClockDay && !oClockMonth)
            return "未到采集时间";
        StringBuilder sbMsg = new StringBuilder();
        List<PowerHourFlow> powerHourFlowList = new ArrayList<>();
        List<PowerDayFlow> powerDayFlowList = new ArrayList<>();
        List<PowerMonthFlow> powerMonthFlowList = new ArrayList<>();
        List<RegDev> ammeterList = regDevMapper.selectList(Wrappers.<RegDev>lambdaQuery().eq(RegDev::getEnergyType, "1"));
        for (RegDev ammeter : ammeterList) {
            Object objData = redisTemplate.opsForHash().get(RedisConstants.REPORT_LIST_KEY, ammeter.getUnitNo());
            if (ObjectUtil.isNull(objData)) {
                String msg = "找不到设备【" + ammeter.getUnitNo() + "】【" + ammeter.getUnitName() + "】的信号数据";
                sbMsg.append(msg);
                log.error(msg);
                continue;
            }
            JSONObject payloadJson = JSONObject.parseObject(objData.toString());
            JSONObject dataJson = payloadJson.getJSONObject(RedisConstants.DATA);
            if (ObjectUtil.isEmpty(dataJson)) {
                String msg = "设备位置编号为:【" + ammeter.getUnitNo() + "】的DATA无数据";
                sbMsg.append(msg);
                log.error(msg);
                continue;
            }
            if (StringUtils.isBlank(dataJson.getString("EP"))) {
                String msg = "设备位置编号为:【" + ammeter.getUnitNo() + "】的通道号【EP】无数据";
                sbMsg.append(msg);
                log.error(msg);
                continue;
            }
            float redisTotVal = dataJson.getBigDecimal("EP").setScale(2, BigDecimal.ROUND_HALF_UP).floatValue();
            float totVal = redisTotVal;
            //计算清零表中的total_value
			List<AmmeterReset> list = ammeterResetService.list(Wrappers.<AmmeterReset>lambdaQuery().eq(AmmeterReset::getUnitNo, ammeter.getUnitNo()));
			if (CollectionUtils.isNotEmpty(list)){
				double sum = list.stream().mapToDouble(AmmeterReset::getTotalValue).sum();
				float sum2 = new BigDecimal(sum).setScale(2, BigDecimal.ROUND_HALF_UP).floatValue();
				totVal += sum2;
			}

            //小时统计
            if (oClock) {
                //查询小时表中最新的一条数据
                PowerHourFlow one = powerHourFlowService.getOne(Wrappers.<PowerHourFlow>lambdaQuery().eq(PowerHourFlow::getUnitNo, ammeter.getUnitNo())
                        .orderByDesc(PowerHourFlow::getTimeValue).last("limit 1"));
                float incr = 0f;
                if (ObjectUtil.isNotEmpty(one)) {
                    if (redisTotVal >= one.getTotalValue()) {
                        incr = totVal - one.getTotalValue();
                        //校验是否跑飞
                        String ratedPower = ammeter.getRatedPower();
                        if (StringUtils.isNotBlank(ratedPower) && !"0".equals(ratedPower)){
                            float v = Float.parseFloat(ratedPower);
                            // 计算小时差
                            long hoursBetween = ChronoUnit.HOURS.between(one.getTimeValue(), LocalDateTime.now().withSecond(0));
                            if (hoursBetween > 0 ){
                                v = v * hoursBetween;
                            }
                            if (incr > v){
                                totVal = one.getTotalValue();
                                incr = 0f;
                                //记录异常表
                                PowerExceptionFlow except = new PowerExceptionFlow();
                                except.setUnitNo(ammeter.getUnitNo());
                                except.setTimeValue(LocalDateTime.now().withSecond(0));
                                except.setTimePartition(Integer.parseInt(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMM"))));
                                except.setMeterValue(redisTotVal);
                                except.setTotalValue(totVal);
                                powerExceptionFlowService.save(except);
                                //调告警接口
                                try {
                                    RunFlyOrLow low = new RunFlyOrLow();
                                    low.setUnitNo(ammeter.getUnitNo());
                                    low.setByName("enable");
                                    low.setHappenTime(LocalDateTime.now().withSecond(0));
                                    low.setAlarmValue(String.valueOf(redisTotVal));
                                    low.setFixedValue(String.valueOf(totVal));
                                    low.setFlag("1");
                                    judgment.inovke(low);
                                }catch (Exception e){
                                    log.error("调用告警接口失败---跑高");
                                }
                            }
                        }
                    } else {
                        log.error("上报值比库里最新数据要小, 设备位置编码:" + ammeter.getUnitNo() +"redisTotVal:" + redisTotVal + "totVal:" + totVal + " one.getTotalValue():" + one.getTotalValue());
                        //redis上报值
                        float redisValue = redisTotVal;
                        redisTotVal = one.getTotalValue();
                        totVal = one.getTotalValue();
                        //记录异常表
                        PowerExceptionFlow except = new PowerExceptionFlow();
                        except.setUnitNo(ammeter.getUnitNo());
                        except.setTimeValue(LocalDateTime.now().withSecond(0));
                        except.setTimePartition(Integer.parseInt(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMM"))));
                        except.setMeterValue(redisValue);
                        except.setTotalValue(totVal);
                        powerExceptionFlowService.save(except);
                        //调告警接口
                        try {
                            RunFlyOrLow low = new RunFlyOrLow();
                            low.setUnitNo(ammeter.getUnitNo());
                            low.setByName("enable");
                            low.setHappenTime(LocalDateTime.now().withSecond(0));
                            low.setAlarmValue(String.valueOf(redisValue));
                            low.setFixedValue(String.valueOf(totVal));
                            low.setFlag("0");
                            judgment.inovke(low);
                        }catch (Exception e){
                            log.error("调用告警接口失败---跑低");
                        }
                    }
                } else {
                    //新加的设备，在2023-11-25日当天添加一条初始化数据。
                    LocalDateTime hourTimeValue = LocalDateTime.of(2023, 11, 25, 0, 0); // 2023年11月25日 0时0分
                    PowerHourFlow hourFlow = new PowerHourFlow(null, ammeter.getUnitNo(), ammeter.getDeviceNo(),
                            hourTimeValue, Integer.parseInt(hourTimeValue.format(DateTimeFormatter.ofPattern("yyyyMM"))), redisTotVal, totVal, redisTotVal,
                            "system", LocalDateTime.now(), null, null, null);
                    powerHourFlowList.add(hourFlow);
                }
                PowerHourFlow hourFlow = new PowerHourFlow(null, ammeter.getUnitNo(), ammeter.getDeviceNo(),
                        LocalDateTime.ofInstant(currentDate.toInstant(), ZoneId.systemDefault()).withMinute(0).withSecond(0).withNano(0),
                        Integer.parseInt(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMM"))),
                        redisTotVal, totVal, incr, "system", LocalDateTime.now(), null, null, null);
                powerHourFlowList.add(hourFlow);

                //如果日表、月表统计中没有这个设备数据，则日表月表中初始化数据
                long dayCount = powerDayFlowService.count(Wrappers.<PowerDayFlow>lambdaQuery()
                        .eq(PowerDayFlow::getUnitNo, ammeter.getUnitNo()));
                if (dayCount == 0) {
                    PowerDayFlow dayFlow = new PowerDayFlow(null, ammeter.getUnitNo(), ammeter.getDeviceNo(),
                            LocalDateTime.of(2023, 11, 25, 0, 0).format(DateTimeFormatter.ofPattern("yyyyMMdd")),
                            totVal, redisTotVal, "system", LocalDateTime.now(), null, null);
                    powerDayFlowList.add(dayFlow);
                }
                long monthCount = powerMonthFlowService.count(Wrappers.<PowerMonthFlow>lambdaQuery()
                        .eq(PowerMonthFlow::getUnitNo, ammeter.getUnitNo()));
                if (monthCount == 0) {
                    PowerMonthFlow monthFlow = new PowerMonthFlow(null, ammeter.getUnitNo(), ammeter.getDeviceNo(),
                            LocalDateTime.of(2023, 11, 25, 0, 0).format(DateTimeFormatter.ofPattern("yyyyMM")),
                            totVal, redisTotVal, "system", LocalDateTime.now(), null, null);
                    powerMonthFlowList.add(monthFlow);
                }

                //判断是否是当天起始整点，如果是当天起始整点，则不添加0点数据。
                if (!oClockDay) {
                    //查询是否有当天0点的数据。
                    String zeroTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd ")) + "00:00:00";
                    long zeroTimeCount = powerHourFlowService.count(Wrappers.<PowerHourFlow>lambdaQuery()
                            .eq(PowerHourFlow::getUnitNo, ammeter.getUnitNo()).eq(PowerHourFlow::getTimeValue, zeroTime));
                    if (zeroTimeCount == 0) {
                        if (ObjectUtil.isNotEmpty(one)) {
                            PowerHourFlow zeroHourFlow = new PowerHourFlow(null, ammeter.getUnitNo(), ammeter.getDeviceNo(),
                                    LocalDate.now().atStartOfDay().withNano(0),
                                    Integer.parseInt(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMM"))),
                                    one.getMeterValue(), one.getTotalValue(), 0f, "system", LocalDateTime.now(), null, null, null);
                            powerHourFlowList.add(zeroHourFlow);
                        } else {
                            PowerHourFlow zeroHourFlow = new PowerHourFlow(null, ammeter.getUnitNo(), ammeter.getDeviceNo(),
                                    LocalDate.now().atStartOfDay().withNano(0),
                                    Integer.parseInt(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMM"))),
                                    redisTotVal, redisTotVal, 0f, "system", LocalDateTime.now(), null, null, null);
                            powerHourFlowList.add(zeroHourFlow);
                        }
                    }
                }
            }

            //日统计
            if (oClockDay) {
                //查询日表中最新的一条数据
                PowerDayFlow one = powerDayFlowService.getOne(Wrappers.<PowerDayFlow>lambdaQuery().eq(PowerDayFlow::getUnitNo, ammeter.getUnitNo())
                        .orderByDesc(PowerDayFlow::getCreateTime).last("limit 1"));
                float incr = 0f;
                if (ObjectUtil.isNotEmpty(one) && (totVal > one.getTotalValue())) {
                    incr = totVal - one.getTotalValue();
                }
                PowerDayFlow dayFlow = new PowerDayFlow(null, ammeter.getUnitNo(), ammeter.getDeviceNo(),
                        LocalDateTime.now().minusDays(1).format(DateTimeFormatter.ofPattern("yyyyMMdd")),
                        totVal, incr, "system", LocalDateTime.now(), null, null);
                powerDayFlowList.add(dayFlow);
            }

            //月统计
            if (oClockMonth) {
                //查询月表中最新的一条数据
                PowerMonthFlow one = powerMonthFlowService.getOne(Wrappers.<PowerMonthFlow>lambdaQuery().eq(PowerMonthFlow::getUnitNo, ammeter.getUnitNo())
                        .orderByDesc(PowerMonthFlow::getCreateTime).last("limit 1"));
                float incr = 0f;
                if (ObjectUtil.isNotEmpty(one) && (totVal > one.getTotalValue())) {
                    incr = totVal - one.getTotalValue();
                }
                PowerMonthFlow monthFlow = new PowerMonthFlow(null, ammeter.getUnitNo(), ammeter.getDeviceNo(),
                        LocalDateTime.now().minusMonths(1).format(DateTimeFormatter.ofPattern("yyyyMM")),
                        totVal, incr, "system", LocalDateTime.now(), null, null);
                powerMonthFlowList.add(monthFlow);
            }
        }

        int hourCount = 0;
        int dayCount = 0;
        int monthCount = 0;
        if (!powerHourFlowList.isEmpty()) {
            hourCount = powerHourFlowService.saveBatch(powerHourFlowList) ? powerHourFlowList.size() : 0;
        }
        if (!powerDayFlowList.isEmpty()) {
            dayCount = powerDayFlowService.saveBatch(powerDayFlowList) ? powerDayFlowList.size() : 0;
        }
        if (!powerMonthFlowList.isEmpty()) {
            monthCount = powerMonthFlowService.saveBatch(powerMonthFlowList) ? powerMonthFlowList.size() : 0;
        }

        String msg = "本次应采集设备" + ammeterList.size() + "个,小时表插入数据" + hourCount + "条，天表插入数据" + dayCount + "条，月表插入数据" + monthCount + "条";
        sbMsg.append(msg);
        return sbMsg.toString();
    }

    /**
     * 电表能耗流水定时任务
     */
    @Scheduled(cron = "0 0/10 * * * ?")
    private String insertWaterFlowHandler() {
        Integer debug = 0;
        log.info("insertWaterFlowHandler------start");
        System.out.println("本次调度时间:" + now());
        Date currentDate = DateUtil.getSecondPoint(now());
        boolean oClock = DateUtil.oClock(new DateTime(currentDate));
        boolean oClockDay = DateUtil.oClockDay(now());
        boolean oClockMonth = DateUtil.oClockMonth(now());
        if (debug.compareTo(1) == 0) {
            oClock = true;
        }
        if (!oClock && !oClockDay && !oClockMonth)
            return "未到采集时间";
        StringBuilder sbMsg = new StringBuilder();
        List<WaterHourFlow> waterHourFlowList = new ArrayList<>();
        List<WaterDayFlow> waterDayFlowList = new ArrayList<>();
        List<WaterMonthFlow> waterMonthFlowList = new ArrayList<>();
        List<RegDev> ammeterList = regDevMapper.selectList(Wrappers.<RegDev>lambdaQuery().eq(RegDev::getEnergyType, "2"));
        for (RegDev ammeter : ammeterList) {
            Object objData = redisTemplate.opsForHash().get(RedisConstants.REPORT_LIST_KEY, ammeter.getUnitNo());
            if (ObjectUtil.isNull(objData)) {
                String msg = "找不到设备【" + ammeter.getUnitNo() + "】【" + ammeter.getUnitName() + "】的信号数据";
                sbMsg.append(msg);
                log.error(msg);
                continue;
            }
            JSONObject payloadJson = JSONObject.parseObject(objData.toString());
            JSONObject dataJson = payloadJson.getJSONObject(RedisConstants.DATA);
            if (StringUtils.isBlank(dataJson.getString("water_consumption"))) {
                String msg = "设备位置编号为:【" + ammeter.getUnitNo() + "】的通道号【water_consumption】无数据";
                sbMsg.append(msg);
                log.error(msg);
                continue;
            }
            float redisTotVal = dataJson.getBigDecimal("water_consumption").setScale(2, BigDecimal.ROUND_HALF_UP).floatValue();
            float totVal = redisTotVal;
            //计算清零表中的total_value
			/*List<AmmeterReset> list = ammeterResetService.list(Wrappers.<AmmeterReset>lambdaQuery().eq(AmmeterReset::getUnitNo, ammeter.getUnitNo()));
			if (CollectionUtils.isNotEmpty(list)) {
				double sum = list.stream().mapToDouble(AmmeterReset::getTotalValue).sum();
				float sum2 = new BigDecimal(sum).setScale(2, BigDecimal.ROUND_HALF_UP).floatValue();
				totVal += sum2;
			}*/

            //小时统计
            if (oClock) {
                //查询小时表中最新的一条数据
                WaterHourFlow one = waterHourFlowService.getOne(Wrappers.<WaterHourFlow>lambdaQuery().eq(WaterHourFlow::getUnitNo, ammeter.getUnitNo())
                        .orderByDesc(WaterHourFlow::getCreateTime).last("limit 1"));
                float incr = 0f;
                if (ObjectUtil.isNotEmpty(one)) {
                    if (redisTotVal >= one.getTotalValue()) {
                        incr = totVal - one.getTotalValue();
                    } else {
                        log.error("设备位置编码:" + ammeter.getUnitNo() + "redisTotVal:" + redisTotVal + "totVal:" + totVal + " one.getTotalValue():" + one.getTotalValue());
                        redisTotVal = one.getTotalValue();
                        totVal = one.getTotalValue();
                    }
                } else {
                    //新加的设备，在2023-11-25日当天添加一条初始化数据。
                    LocalDateTime hourTimeValue = LocalDateTime.of(2023, 11, 25, 0, 0); // 2023年11月25日 0时0分
                    WaterHourFlow hourFlow = new WaterHourFlow(null, ammeter.getUnitNo(), ammeter.getDeviceNo(),
                            hourTimeValue, Integer.parseInt(hourTimeValue.format(DateTimeFormatter.ofPattern("yyyyMM"))), redisTotVal, totVal, redisTotVal,
                            "system", LocalDateTime.now(), null, null);
                    waterHourFlowList.add(hourFlow);
                }
                WaterHourFlow hourFlow = new WaterHourFlow(null, ammeter.getUnitNo(), ammeter.getDeviceNo(),
                        LocalDateTime.ofInstant(currentDate.toInstant(), ZoneId.systemDefault()).withMinute(0).withSecond(0).withNano(0),
                        Integer.parseInt(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMM"))),
                        redisTotVal, totVal, incr, "system", LocalDateTime.now(), null, null);
                waterHourFlowList.add(hourFlow);

                //如果日表、月表统计中没有这个设备数据，则日表月表中初始化数据
                long dayCount = waterDayFlowService.count(Wrappers.<WaterDayFlow>lambdaQuery()
                        .eq(WaterDayFlow::getUnitNo, ammeter.getUnitNo()));
                if (dayCount == 0) {
                    WaterDayFlow dayFlow = new WaterDayFlow(null, ammeter.getUnitNo(), ammeter.getDeviceNo(),
                            LocalDateTime.of(2023, 11, 25, 0, 0).format(DateTimeFormatter.ofPattern("yyyyMMdd")),
                            totVal, redisTotVal, "system", LocalDateTime.now(), null, null);
                    waterDayFlowList.add(dayFlow);
                }
                long monthCount = waterMonthFlowService.count(Wrappers.<WaterMonthFlow>lambdaQuery()
                        .eq(WaterMonthFlow::getUnitNo, ammeter.getUnitNo()));
                if (monthCount == 0) {
                    WaterMonthFlow monthFlow = new WaterMonthFlow(null, ammeter.getUnitNo(), ammeter.getDeviceNo(),
                            LocalDateTime.of(2023, 11, 25, 0, 0).format(DateTimeFormatter.ofPattern("yyyyMM")),
                            totVal, redisTotVal, "system", LocalDateTime.now(), null, null);
                    waterMonthFlowList.add(monthFlow);
                }

                //判断是否是当天起始整点，如果是当天起始整点，则不添加0点数据。
                if (!oClockDay) {
                    //查询是否有当天0点的数据。
                    String zeroTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd ")) + "00:00:00";
                    long zeroTimeCount = waterHourFlowService.count(Wrappers.<WaterHourFlow>lambdaQuery()
                            .eq(WaterHourFlow::getUnitNo, ammeter.getUnitNo()).eq(WaterHourFlow::getTimeValue, zeroTime));
                    if (zeroTimeCount == 0) {
                        if (ObjectUtil.isNotEmpty(one)) {
                            WaterHourFlow zeroHourFlow = new WaterHourFlow(null, ammeter.getUnitNo(), ammeter.getDeviceNo(),
                                    LocalDate.now().atStartOfDay().withNano(0),
                                    Integer.parseInt(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMM"))),
                                    one.getMeterValue(), one.getTotalValue(), 0f, "system", LocalDateTime.now(), null, null);
                            waterHourFlowList.add(zeroHourFlow);
                        } else {
                            WaterHourFlow zeroHourFlow = new WaterHourFlow(null, ammeter.getUnitNo(), ammeter.getDeviceNo(),
                                    LocalDate.now().atStartOfDay().withNano(0),
                                    Integer.parseInt(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMM"))),
                                    redisTotVal, redisTotVal, 0f, "system", LocalDateTime.now(), null, null);
                            waterHourFlowList.add(zeroHourFlow);
                        }
                    }
                }
            }

            //日统计
            if (oClockDay) {
                //查询日表中最新的一条数据
                WaterDayFlow one = waterDayFlowService.getOne(Wrappers.<WaterDayFlow>lambdaQuery().eq(WaterDayFlow::getUnitNo, ammeter.getUnitNo())
                        .orderByDesc(WaterDayFlow::getCreateTime).last("limit 1"));
                float incr = 0f;
                if (ObjectUtil.isNotEmpty(one) && (totVal > one.getTotalValue())) {
                    incr = totVal - one.getTotalValue();
                }
                WaterDayFlow dayFlow = new WaterDayFlow(null, ammeter.getUnitNo(), ammeter.getDeviceNo(),
                        LocalDateTime.now().minusDays(1).format(DateTimeFormatter.ofPattern("yyyyMMdd")),
                        totVal, incr, "system", LocalDateTime.now(), null, null);
                waterDayFlowList.add(dayFlow);
            }

            //月统计
            if (oClockMonth) {
                //查询月表中最新的一条数据
                WaterMonthFlow one = waterMonthFlowService.getOne(Wrappers.<WaterMonthFlow>lambdaQuery().eq(WaterMonthFlow::getUnitNo, ammeter.getUnitNo())
                        .orderByDesc(WaterMonthFlow::getCreateTime).last("limit 1"));
                float incr = 0f;
                if (ObjectUtil.isNotEmpty(one) && (totVal > one.getTotalValue())) {
                    incr = totVal - one.getTotalValue();
                }
                WaterMonthFlow monthFlow = new WaterMonthFlow(null, ammeter.getUnitNo(), ammeter.getDeviceNo(),
                        LocalDateTime.now().minusMonths(1).format(DateTimeFormatter.ofPattern("yyyyMM")),
                        totVal, incr, "system", LocalDateTime.now(), null, null);
                waterMonthFlowList.add(monthFlow);
            }
        }

        int hourCount = 0;
        int dayCount = 0;
        int monthCount = 0;
        if (!waterHourFlowList.isEmpty()) {
            hourCount = waterHourFlowService.saveBatch(waterHourFlowList) ? waterHourFlowList.size() : 0;
        }
        if (!waterDayFlowList.isEmpty()) {
            dayCount = waterDayFlowService.saveBatch(waterDayFlowList) ? waterDayFlowList.size() : 0;
        }
        if (!waterMonthFlowList.isEmpty()) {
            monthCount = waterMonthFlowService.saveBatch(waterMonthFlowList) ? waterMonthFlowList.size() : 0;
        }

        String msg = "本次应采集设备" + ammeterList.size() + "个,小时表插入数据" + hourCount + "条，天表插入数据" + dayCount + "条，月表插入数据" + monthCount + "条";
        sbMsg.append(msg);
        return sbMsg.toString();
    }

    /**
     * 电表能耗流水费用定时任务
     */
    @Scheduled(cron = "0 5 * * * ?")
    public String insertCostFlowHandler() {
        log.info("insertCostFlowHandler------start");
        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
        List<EnergyRateManage> energyList = energyRateManageService.getBaseMapper().selectList(Wrappers.<EnergyRateManage>lambdaQuery().eq(EnergyRateManage::getEnergyType, "1"));
        if (energyList != null) {
            energyList.stream().forEach(item -> {
                        item.setFlowList(energyRateFlowService.getBaseMapper().selectList(Wrappers.<EnergyRateFlow>lambdaQuery().eq(EnergyRateFlow::getRateId, item.getRateId())));
                    }
            );
            //设备
            List<RegDev> ammeterList = regDevMapper.selectList(Wrappers.<RegDev>lambdaQuery().eq(RegDev::getEnergyType, "1"));
            for (RegDev ammeter : ammeterList) {
                //查询小时表中最新的一条数据
                PowerHourFlow one = powerHourFlowService.getCostOne(ammeter.getUnitNo());
                if (ObjectUtil.isNotEmpty(one)) {
                    //费率配置循环对比时间
                    energyList.stream().forEach(f -> {
                        LocalDateTime startTime = LocalDateTime.parse(f.getRateStartTime(), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
                        LocalDateTime endTime = LocalDateTime.parse(f.getRateEndTime(), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
                        if (one.getTimeValue().isAfter(startTime) && one.getTimeValue().isBefore(endTime)) {
                            f.getFlowList().forEach(l -> {
                                try {
                                    Date startDate = sdf.parse(l.getRateStartTime());
                                    Date endDate = sdf.parse(l.getRateEndTime());
                                    Date oneDate = sdf.parse(one.getSeconds());
                                    boolean isInRange = oneDate.after(startDate) && oneDate.before(endDate) || oneDate.equals(startDate);
                                    if (isInRange) {
                                        CostHourFlow costHourFlow = new CostHourFlow();
                                        costHourFlow.setUnitNo(one.getUnitNo());
                                        costHourFlow.setDeviceNo(one.getDeviceNo());
                                        costHourFlow.setTimeValue(one.getTimeValue());
                                        costHourFlow.setTimePartition(one.getTimePartition());
                                        costHourFlow.setTotalValue(one.getTotalValue());
                                        costHourFlow.setIncrValue(one.getIncrValue());
                                        costHourFlow.setRateType(l.getRateType());
                                        costHourFlow.setPrice(l.getPrice());
                                        BigDecimal sumPrice = BigDecimal.valueOf(one.getIncrValue()).multiply(l.getPrice());
                                        costHourFlow.setSumPrice(new BigDecimal(String.valueOf(sumPrice)).setScale(2, BigDecimal.ROUND_HALF_UP));
                                        CostHourFlow selectOne = costHourFlowService.getBaseMapper().selectOne(Wrappers.<CostHourFlow>lambdaQuery()
                                                .eq(CostHourFlow::getTimeValue, one.getTimeValue())
                                                .eq(CostHourFlow::getUnitNo, one.getUnitNo()));
                                        if (selectOne == null) {
                                            costHourFlowService.getBaseMapper().insert(costHourFlow);
                                        }
                                    }
                                } catch (ParseException e) {
                                    throw new RuntimeException(e);
                                }
                            });
                        }
                    });
                }
            }
        }
        return null;
    }
}
